/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { extend } from 'umi-request';
import { history } from 'umi';
import { message } from '@@/plugin-request/ui';

const loginPath = '/user/login';

/**
 * 配置request请求时的默认参数
 */
const request = extend({
  prefix: process.env.NODE_ENV === 'production' ? 'http://124.222.131.28:8080' : undefined,
  timeout: 1000,
  credentials: 'include',
});

/**
 * 所有响应拦截器
 */
request.interceptors.response.use(async (response, options): Promise<any> => {
  const res = await response.clone().json();

  if (res.code === 0) {
    return res.data;
  }
  if (res.code === 40100) {
    message.error('请先登录');
    history.push(loginPath);
  } else {
    message.error(res.description);
  }
  return res.data;
});

export default request;
